package com.bryant.demo05.ui.home

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bryant.demo05.R
import com.bryant.demo05.WeatherGlobal
import com.bryant.demo05.base.BaseBindingFragment
import com.bryant.demo05.bean.ChangeCityBean
import com.bryant.demo05.databinding.FragmentHomeBinding
import com.bryant.demo05.event.ChangeCityClickEvent
import com.bryant.demo05.ui.detail.DetailActivity
import com.bryant.demo05.utils.WeatherUtils
import com.qweather.sdk.response.weather.WeatherHourlyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(), HomeView {
    // 1. 初始化 homePresenter
    private var homePresenter: HomePresenter? = null

    // 2. 实现周期性时间更新
    // 创建与主线程关联的Handler实例，用于执行定时任务
    private val handler = Handler(Looper.getMainLooper())

    // 定义Runnable对象，用于周期性更新当前时间
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            getCurrentTime()  // 调用方法更新界面显示的时间
            handler.postDelayed(this, 1000) // 每隔1000毫秒（即1秒）再次执行此任务
        }
    }

    private var dialog: ChangeCityDialog? = null

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }
    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }
    /**
     * 订阅ChangeCityClickEvent事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun changeCitySuccess(event: ChangeCityClickEvent){
        /**
         * 切换城市成功，刷新数据
         */
        event.changeCityBean.let {
            refreshLocationWeatherData(it.cityName, it.latitude.toString(), it.longitude.toString())
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        if (binding.topBar.tvCityName.text.isEmpty()) {
            refreshLocationWeatherData(
                WeatherGlobal.getCityName(),
                WeatherGlobal.getLatitude(),
                WeatherGlobal.getLongitude()
            )
        }
    }

    override fun initBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, parent, false)
    }

    override fun initView() {
        homePresenter = HomePresenter(this, HomeInteractor())

        // 1. 设置点击事件
        setupClickListener()

        // 2. 设置未来24小时卡片布局和适配器
        binding.hourlyForecast.rvHourlyForecast.apply {
            // 2.1 设置布局管理器为水平方向
            layoutManager = LinearLayoutManager(
                context,
                LinearLayoutManager.HORIZONTAL,
                false
            )

            // 2.2 设置适配器
            adapter = HourTempAdapter()

            // 2.3 设置间距
            if (binding.hourlyForecast.rvHourlyForecast.itemDecorationCount == 0){
                binding.hourlyForecast.rvHourlyForecast.addItemDecoration(
                  object : RecyclerView.ItemDecoration (){
                      override fun getItemOffsets(
                          outRect: Rect,
                          view: View,
                          parent: RecyclerView,
                          state: RecyclerView.State
                      ) {
                          super.getItemOffsets(outRect, view, parent, state)

                          // 获取当前item在适配器中的位置
                          val position = parent.getChildAdapterPosition(view)

                          if (position == 0) {
                              // 如果是第一个item，则左边没有间隔
                              outRect.left = 0
                          } else {
                              // 对于其他item，在左侧添加8dp的间距，并将其转换为像素
                              context?.let {
                                  outRect.left = WeatherUtils.dip2px(it, 8f)
                              }
                          }
                      }
                  }
                )
            }
        }
    }


    @SuppressLint("SetTextI18n")
    override fun getCurrentWeatherSuccess(response: WeatherNowResponse) {
        hideLoading()
        stopUpdateTime()
        getCurrentTime()
        startUpdateTime()

        // ------------------- 卡片渲染工作 ----------------------------
        // 1. 先让当前卡片显示
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = View.VISIBLE
        // 2. 渲染更新时间
        binding.currentWeatherCard.tvRefreshTime.text = WeatherUtils.formatTime(response.updateTime) + "更新"
        // 3. 渲染温度
        binding.currentWeatherCard.tvTemperature.text = response.now.temp
        // 4. 让温度单位显示
        binding.currentWeatherCard.tvDegreeSymbol.visibility = View.VISIBLE

        // 4. 根据当前天气状况的图标代码， 绘制对应的天气图标
        context?.let {
            var iconCode = "_" + response.now.icon.replace("-", "_")
            if (WeatherUtils.isDrawableInRClass(it, iconCode)) {
               val drawble = WeatherUtils.getDrawableByName(it, iconCode)
                drawble?.let {
                    binding.currentWeatherCard.ivWeatherIcon.setImageDrawable(drawble)
                }
                binding.currentWeatherCard.ivWeatherIcon.visibility = View.VISIBLE
            } else {
                binding.currentWeatherCard.ivWeatherIcon.visibility = View.GONE
            }
        }

        // 5. 渲染天气描述
        //数据拼接，如 晴 | 北风3级 | 当前体感20度
        var constructText = ""
        if (response.now.text.isNotEmpty()) {
            constructText += response.now.text
        }
        if (response.now.windDir.isNotEmpty() && response.now.windScale.isNotEmpty()) {
            constructText += " | " + response.now.windDir + response.now.windScale + "级"
        }
        if (response.now.feelsLike.isNotEmpty()) {
            constructText += " | 当前体感" + response.now.feelsLike + "°"
        }
        if (constructText.isNotEmpty()) {
            binding.currentWeatherCard.tvWeatherCondition.text = constructText
        } else {
            binding.currentWeatherCard.tvWeatherCondition.text = "暂无数据"
        }

        binding.currentWeatherCard.tvHumidity.text = response.now.humidity + "%"
        binding.currentWeatherCard.tvWindSpeed.text = response.now.windSpeed
        binding.currentWeatherCard.tvPressure.text = response.now.pressure
    }

    override fun getCurrentWeatherFailed(message: String) {
        hideLoading()
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = View.GONE
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show()
    }

    // 24小时天气获取成功
    @SuppressLint("SuspiciousIndentation")
    override fun getHourlyWeatherDataSuccess(response: WeatherHourlyResponse) {
      binding.hourlyForecast.root.visibility = View.VISIBLE
        // 提交数据
        response.hourly?.let { hourlyList ->
            (binding.hourlyForecast.rvHourlyForecast.adapter as HourTempAdapter).submitList(hourlyList)
        }
    }

    override fun getHourlyWeatherDataFailure(errorResponse: String) {
        binding.hourlyForecast.root.visibility = View.GONE
    }

    override fun refreshCityList(cityList: MutableList<ChangeCityBean>) {
      // 给城市弹层传递数据
        dialog?.refreshCityList(cityList)
    }



    // ------------------------- 刷新数据 ----------------------------------
    fun refreshLocationWeatherData(
        cityName: String,
        latitude: String,
        longitude: String
    ) {
        // 设置城市名称
        binding.topBar.tvCityName.text = cityName
        homePresenter?.setCityLocationParams(cityName, latitude, longitude)
        showLoading()
        homePresenter?.requestMainWeatherData()
    }

    // 获取当前时间
    private fun getCurrentTime() {
        var currentTime = System.currentTimeMillis()
        binding.topBar.tvCurrentTime.text =
            WeatherUtils.formatUTC(currentTime, "yyyy-MM-dd HH:mm:ss")
        binding.currentWeatherCard.tvWeekday.text = WeatherUtils.formatUTC(currentTime, "EEEE")
    }

    // 开始更新时间
    private fun startUpdateTime() {
        handler.post(updateTimeRunnable)
    }

    // 停止更新时间
    private fun stopUpdateTime() {
        handler.removeCallbacks(updateTimeRunnable)
    }

    // 刷新天气
    private fun setupClickListener() {
        // 1. 点我刷新
        binding.currentWeatherCard.btnRealTime.setOnClickListener{
            showLoading()
            homePresenter?.requestMainWeatherData()
        }

        // 2. 监听城市顶部点击
        binding.topBar.tvCityName.setOnClickListener {
            homePresenter?.requestTopCityListData()
            // 创建城市弹层
            showChangeDialog()
        }

        // 3. 点击卡片跳转至详情页
        binding.currentWeatherCard.llCurrentWeatherContainer.setOnClickListener {
            val intent = Intent(mActivity, DetailActivity::class.java)
            // 携带参数跳转
            intent.putExtra("cityName", homePresenter?.getCurrentShowCityName())
            intent.putExtra("latitude", homePresenter?.getCurrentShowLatitude())
            intent.putExtra("longitude", homePresenter?.getCurrentShowLongitude())
            startActivity(intent)
        }
    }


    /**
     * 显示切换城市的dialog
     */
    fun showChangeDialog(){
        mActivity?.let {
            dialog = ChangeCityDialog(it, R.style.BottomSheetDialog_Immersion)
            dialog?.setOnDismissListener {
                if(dialog != null){
                    dialog = null
                }
            }
            dialog?.show()
        }
    }


}